package com.writing.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ObjectMetadata;
import com.writing.config.OssConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * 阿里云OSS工具类
 */
@Slf4j
@Component
public class OssUtil {
    
    @Autowired
    private OssConfig ossConfig;
    
    /**
     * 上传文件到OSS
     * 
     * @param file 要上传的文件
     * @param folder 文件夹路径（可选）
     * @return 文件的访问URL
     */
    public String uploadFile(MultipartFile file, String folder) {
        // 创建OSS客户端
        OSS ossClient = new OSSClientBuilder().build(
            ossConfig.getEndpoint(),
            ossConfig.getAccessKeyId(),
            ossConfig.getAccessKeySecret()
        );
        
        try {
            // 生成文件名
            String fileName = generateFileName(file.getOriginalFilename(), folder);
            
            // 设置文件元数据
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentLength(file.getSize());
            metadata.setContentType(file.getContentType());
            
            // 上传文件
            InputStream inputStream = file.getInputStream();
            ossClient.putObject(ossConfig.getBucketName(), fileName, inputStream, metadata);
            
            // 返回文件URL
            String fileUrl = ossConfig.getUrlPrefix() + fileName;
            log.info("文件上传成功: {}", fileUrl);
            return fileUrl;
            
        } catch (IOException e) {
            log.error("文件上传失败", e);
            throw new RuntimeException("文件上传失败: " + e.getMessage());
        } finally {
            // 关闭OSS客户端
            ossClient.shutdown();
        }
    }
    
    /**
     * 删除OSS文件
     * 
     * @param fileUrl 文件URL
     */
    public void deleteFile(String fileUrl) {
        if (fileUrl == null || !fileUrl.startsWith(ossConfig.getUrlPrefix())) {
            return;
        }
        
        // 创建OSS客户端
        OSS ossClient = new OSSClientBuilder().build(
            ossConfig.getEndpoint(),
            ossConfig.getAccessKeyId(),
            ossConfig.getAccessKeySecret()
        );
        
        try {
            // 提取文件名
            String fileName = fileUrl.substring(ossConfig.getUrlPrefix().length());
            
            // 删除文件
            ossClient.deleteObject(ossConfig.getBucketName(), fileName);
            log.info("文件删除成功: {}", fileUrl);
            
        } catch (Exception e) {
            log.error("文件删除失败: {}", fileUrl, e);
        } finally {
            // 关闭OSS客户端
            ossClient.shutdown();
        }
    }
    
    /**
     * 生成文件名
     * 
     * @param originalFilename 原始文件名
     * @param folder 文件夹
     * @return 生成的文件名
     */
    private String generateFileName(String originalFilename, String folder) {
        // 获取文件扩展名
        String extension = "";
        if (originalFilename != null && originalFilename.contains(".")) {
            extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        }
        
        // 生成日期路径
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        String datePath = sdf.format(new Date());
        
        // 生成UUID文件名
        String uuid = UUID.randomUUID().toString().replace("-", "");
        
        // 组合文件路径
        StringBuilder fileName = new StringBuilder();
        if (folder != null && !folder.isEmpty()) {
            fileName.append(folder).append("/");
        }
        fileName.append(datePath).append("/").append(uuid).append(extension);
        
        return fileName.toString();
    }
}
